<template>
	<view class="page">
		<div class="search-wrap">
			<!-- <div class="input">
				<input type="text" maxlength="10" v-model="searchContent" placeholder="请输入城市名称" @confirm="changeSearch(searchContent)" />
			</div> -->
			<uni-search-bar ref="search" maxlength="10" placeholder="请输入城市名称" @confirm="changeSearch" @clear="getBusStationList"
			 radius="80" bgColor="#fff" clearButton="always" cancelButton="none" />
		</div>
		
		<view class="history_list-wrap tp-w690" v-if="historyList.length">
			<view class="top">
				<view class="l-top">历史记录</view>
				<view class="r-top-wrap" @click="handleClearHistory">
					<view class="icon">
						<uni-icons type="trash" color="#999999" size="20"></uni-icons>
					</view>
					<view>清除历史</view>
				</view>
			</view>
			<view class="history_list">
				<view 
					class="history_item"
					v-for="(it_h,in_h) in historyList"
					:key="in_h"
				>
					<text @click="tagSrarch(it_h)">{{it_h.value}}</text>
					<view class="icon" @click="handleClearHistoryItem(it_h.id)"><uni-icons type="closeempty" color="#999999"></uni-icons></view>
				</view>
			</view>
		</view>
		
		<view class="location-wrap tp-w690">
			<view class="location_top">当前城市</view>
			<text class="location_address" @click="nowCity">{{curLocation}}</text>
		</view>
		
		<view class="address-list">
			<view 
				class="address-item"
				:class="{active: it_a.value && it_a.value.match(/[A-Z]/)}"
				v-for="(it_a,in_a) in addressList"
				:key="in_a"
				@click.stop.prevent="handleChooseAddress(it_a, in_a)"
			>
				<text>{{it_a.value}}</text>
				<view class="search-address-list" v-if="curAddressIndex===in_a">
				</view>
			</view>
		</view>
		
		<view v-if="choosedAddressInfo.value" class="confirm-btn" @click="handleConfirmChooseAddress">确定</view>
	</view>
</template>

<script>
	import searchMatch from '../../utils/searchMatch.js'
	import $DB from '../../utils/debounce.js'
	export default {
		components: {
			
		},
		data() {
			return {
				curLocation: '', // 当前地址
				travelsStatus: '', // to出发地选择 | form目的地选择
				searchContent: '',
				historyList: [], // 搜索历史记录
				addressList: [],
				curAddressIndex: 0,
				choosedAddressInfo: {},
				searchedAddressList: []
			};
		},
		onLoad(opt) {
			this.travelsStatus = opt && opt.travelsStatus
			this.getBusStationList()
			this.getCurLocation()
			this.updateSearchHistoryList() // 获取历史搜索站点记录
		},
		onShow() {
			
		},
		methods: {
			getCurLocation() {
				this.curLocation = this.$store.getters.getCurLocation.city
			},
			changeSearch(e) { // 用户点击键盘上的搜索按钮时触发
			let str = e.detail && e.detail.value || e.value || e
			this.searchContent = str
			this.getBusStationList()
				// let str =  e.detail&&e.detail.value || e
				// this.$store.commit('upSearchHistoryList', str)
				// this.addressList.forEach((item,index) => {
				// 	if (item.value.indexOf(str)!=-1
				// 		|| searchMatch.getFullChars(item.value).toLowerCase().indexOf(str)!=-1
				// 		|| searchMatch.getCamelChars(item.value).toLowerCase().indexOf(str) != -1) {
				// 		this.searchContent = ''
				// 	}
				// })
				// setTimeout(() => {
				// 	this.scrollTo()
				// },200)
			},
			// 点击历史的标签
			tagSrarch(val) {
				this.choosedAddressInfo = val
				this.handleConfirmChooseAddress()
			},
			// 点击现在的城市
			nowCity() {
				this.addressList.forEach((item, index) => {
					if (item.value == this.curLocation) {
						this.handleChooseAddress(item, index)
					}
				})
				this.scrollTo()
			},
			handleChooseAddress(item,i) {
				this.$store.commit('upChoosedRentCity', {[this.travelsStatus]: item})
				uni.navigateBack({delta: 1});
			},
			// q清除历史
			handleClearHistory() {
				this.$http.get(this.$api.delSearchHistorys + '?type=3').then(res => {
					if (res.code == 200) { // 保存更新历史搜索记录
						this.updateSearchHistoryList()
					}
				})
				// // this.$store.commit('delSearchHistoryList');
				// let arr = []
				// this.historyList.forEach(item => {
				// 	arr.push(item.id)
				// })
				// let ids = arr.join()
				// this.$http.get(this.$api.delSearchHistory + '?ids=' + ids).then(res => {
				// 	if (res.code == 200) { // 保存更新历史搜索记录
				// 		this.updateSearchHistoryList()
				// 	}
				// })
			},
			// 删除单个历史
			handleClearHistoryItem(id) {
				// this.$store.commit('delSearchHistoryList', i)
				this.$http.get(this.$api.delSearchHistory + '?ids=' + id).then(res => {
					if (res.code == 200) { // 保存更新历史搜索记录
						this.updateSearchHistoryList()
					}
				})
			},
			handleConfirmChooseAddress() { // 确定选择地址
				// this.$http.get(this.$api.saveSearchHistory + '?type=1&stationName=' + this.choosedAddressInfo.value).then(res => {
				// 	if (res.code == 200) { // 保存更新历史搜索记录
				// 		// this.updateSearchHistoryList()
				// 	}
				// })
				if (this.travelsStatus) {
					this.$store.commit('upChoosedRentCity', {[this.travelsStatus]: this.choosedAddressInfo})
					uni.navigateBack({delta: 1})
				}
			},
			// 更新历史信息
			updateSearchHistoryList() {
				// this.historyList = this.$store.getters.getSearchHistoryList
				// this.$http.get(this.$api.getBusStation, {type:1}).then(res => {
				// 	if (res.code === 200) {
				// 		this.historyList = res.data.searchList
				// 	}
				// })
				this.$http.get(this.$api.saveSearchHistory + '?type=3').then(res => {
					if (res.code === 200) {
						this.historyList = res.data.searchList
					}
				})
			},
			scrollTo() {
				uni.createSelectorQuery().select(".address-list").boundingClientRect(data=>{//目标节点
			　　uni.createSelectorQuery().select(".search-address-list").boundingClientRect((res)=>{//最外层盒子节点
		　　　　uni.pageScrollTo({
		　　　　　　duration:0,//过渡时间必须为0，uniapp bug，否则运行到手机会报错
		　　　　　　scrollTop:res.top - data.top,//滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
		　　　　})
			　　}).exec()
				}).exec();
			},
			getBusStationList() {
				this.$http.get(this.$api.getBusStation,{
					type: 3,
					stationName:this.searchContent
				}).then(res => {
					if (res.code === 200) {
						let arr = []
						let arr_tmp = []
						let cityMap = res.data.cityMap
						// this.historyList = res.data.searchList
						let keys = Object.keys(res.data.cityMap)
						keys.forEach(key => {
							for(let i = 0; i < cityMap[key].length; i++) {
								arr_tmp.push(key)
							}
						})
						keys.forEach(key => {
							cityMap[key].forEach(item => { // 首字母所包含的数据
								if (arr_tmp.includes(key)) {
									// let city = item
									let city = Object.keys(item)[0]
									let obj = {
										label: city,
										value: city,
										sub: []
									}
									item[city].forEach(sub => {
										obj.sub.push({
											label: sub.value,
											value: sub.value,
											id: sub.id
										})
									})
									arr.push({
										label: key,
										value: key
									},obj)
								}
							})
						})
						function uniq(arr) {
							var tmp = new Set(arr.map(item => JSON.stringify(item)));
							return Array.from(tmp).map(item => JSON.parse(item));
						}
						this.addressList =  uniq(arr)
						// this.changeSearch(this.curLocation)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.page {
	padding-top: 108rpx;
	padding-bottom: 120rpx;
}
.search-wrap {
	background-color: $blue;
	// padding: 12rpx 0;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 2;
	padding: 16rpx;
	.input {
		width: 690rpx;
		margin: 0 auto;
		height: 56rpx;
		line-height: 56rpx;
		border-radius: 28rpx;
		color: #CCCCCC;
		background: #fff url(../../static/imgs/icons/search-icon.png) no-repeat left 238rpx center;
		background-size: 28rpx 28rpx;
		padding-left: 275rpx;
		box-sizing: border-box;
	}
}

.history_list-wrap {
	.top {
		display: flex;
		justify-content: space-between;
		align-items: center;
		color: #666;
		font-size: 26rpx;
		padding: 40rpx 0 20rpx;
		.r-top-wrap {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			.icon {
				margin-top: 5rpx;
				margin-right: 20rpx;
			}
		}
	}
	.history_list {
		display: flex;
		flex-wrap: wrap;
		.history_item {
			font-size: 28rpx;
			padding: 19rpx 60rpx 19rpx 21rpx;
			background-color: #fff;
			border-radius: 8rpx;
			display: flex;
			margin: 0 20rpx 20rpx 0;
			position: relative;
			.icon {
				position: absolute;
				top: 50%;
				transform: translateY(-50%);
				right: 19rpx;
			}
		}
	}
}

.location-wrap {
	margin-bottom: 20rpx;
	.location_top {
		margin: 20rpx auto;
		text-align: left;
		font-size: 26rpx;
		color: #666;
	}
	.location_address {
		display: inline-block;
		font-size: 28rpx;
		padding: 19rpx 21rpx;
		background-color: #fff;
		border-radius: 8rpx;
	}
}

.address-list {
	.address-item {
		background-color: #fff;
		padding: 30rpx;
		border-bottom: 1px solid #f5f5f5;
		font-size: 30rpx;
		&.active {
			font-size: 36rpx;
			background-color: #f5f5f5;
		}
	}
}

.search-address-list {
	.search-address-item {
		background-color: #fff;
		padding: 0 30rpx;
		height: 92rpx;
		border-bottom: 1px solid #f5f5f5;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		&:last-child {
			border: none;
		}
		&.active {
			font-size: 36rpx;
			background-color: #f5f5f5;
		}
	}
}
.confirm-btn {
	width:750rpx;
	height:98rpx;
	line-height: 98rpx;
	text-align: center;
	background:$blue;
	font-size:32rpx;
	color: #fff;
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
}
</style>
